/* eslint-disable @typescript-eslint/no-explicit-any */
import React from 'react';
import type { FormProps } from 'antd';
import { Button, Form, Input, Space, Table, Tag, message, Select } from 'antd';
import type { TableProps } from 'antd';
import LayoutComp from './layout';
import CryptoUtil from './encrypt';
import axios from 'axios';
const { Option } = Select;
type FieldType = {
  type?: string;
  password?: string;
};
interface DataType {
  key: string;
  name: string;
  age: number;
  uid: string;
  address: string;
  tags: string[];
}

const data: DataType[] = [
  {
    uid: '0961',
    key: '1',
    name: 'John Brown',
    age: 32,
    address: 'New York No. 1 Lake Park',
    tags: ['nice', 'developer'],
  },
  {
    uid: '0962',
    key: '2',
    name: 'Jim Green',
    age: 42,
    address: 'London No. 1 Lake Park',
    tags: ['loser'],
  },
  {
    uid: '0963',
    key: '3',
    name: 'Joe Black',
    age: 32,
    address: 'Sydney No. 1 Lake Park',
    tags: ['cool', 'teacher'],
  },
];
const onFinishFailed: FormProps<FieldType>['onFinishFailed'] = (errorInfo) => {
  console.log('Failed:', errorInfo);
};
const App: React.FC = () => {
  const secretKey = 'byte-movie'; // 密钥，前后端共享
  const salt = 'douyin'; // 盐值，前后端共享
  const cryptoUtil = new CryptoUtil(secretKey, salt);
  // const [value, setValue] = useState<string>('');
  // const [decryptedValue, setDecryptedText] = useState<string>('');
  // 异步函数，用于读取剪贴板中的内容
  // async function readTextFromClipboard() {
  //   if (navigator.clipboard) {
  //     try {
  //       const text = await navigator.clipboard.readText();
  //       console.log('从剪贴板读取的文本：', text);
  //       return text;
  //     } catch (err) {
  //       console.error('无法读取剪贴板内容：', err);
  //     }
  //   }
  // }
  // 异步函数，用于写入文本到剪贴板
  async function writeTextToClipboard(text: string) {
    if (navigator.clipboard) {
      try {
        await navigator.clipboard.writeText(text);
        console.log('文本已复制到剪贴板：', text);
      } catch (err) {
        console.error('无法写入剪贴板：', err);
      }
    }
  }
  const handleEncrypted = (record: DataType) => {
    console.log('record: ', record);
    // 使用加密工具加密密码
    try {
      const encryptPassword = cryptoUtil.encrypt(record.uid);
      message.success('邀请码已生成，您可以直接粘贴');
      writeTextToClipboard(encryptPassword);
      // setValue(encryptPassword)
      console.log('Decrypted Password:', encryptPassword);
    } catch (error) {
      console.error('Error decrypting password:', error);
    }
  }
  const columns: TableProps<DataType>['columns'] = [
    {
      title: 'Uid',
      dataIndex: 'uid',
      key: 'uid',
    },
    {
      title: '用户名',
      dataIndex: 'name',
      key: 'name',
      render: (text) => <div>{text}</div>,
    },
    {
      title: 'Age',
      dataIndex: 'age',
      key: 'age',
    },
    {
      title: 'Address',
      dataIndex: 'address',
      key: 'address',
    },
    {
      title: 'Tags',
      key: 'tags',
      dataIndex: 'tags',
      render: (_, { tags }) => (
        <>
          {tags.map((tag) => {
            let color = tag.length > 5 ? 'geekblue' : 'green';
            if (tag === 'loser') {
              color = 'volcano';
            }
            return (
              <Tag color={color} key={tag}>
                {tag.toUpperCase()}
              </Tag>
            );
          })}
        </>
      ),
    },
    {
      title: 'Action',
      key: 'action',
      render: (_: any, record) => (
        <Space size="middle">
          <Button onClick={() => handleEncrypted(record)} type='primary'>生成邀请码</Button>
        </Space>
      ),
    },
  ];
  const onFinish: FormProps<FieldType>['onFinish'] = (values) => {
    if (values.type && values.password) {
      console.log('Success:', values);
      try {
        // setDecryptedText('');
        axios.post('/api/api/signup', {
          type: values.type,
          password: values.password,
        })
          .then((response) => {
            const { code, data, msg } = response.data;
            if (code === 200) {
              console.log('Response:', data);
              message.success(msg);
            }
          })
          .catch((error) => {
            console.error('Error:', error);
            message.error('注册失败');
          });
      } catch (error) {
        console.error('Error encrypting password:', error);
      }
    }
  };

  // const handleDecrypted = () => {
  //   // 使用加密工具解密密码
  //   try {
  //     const decryptedPassword = cryptoUtil.decrypt(value);
  //     // setDecryptedText(decryptedPassword)
  //     console.log('Decrypted Password:', decryptedPassword);
  //   } catch (error) {
  //     console.error('Error decrypting password:', error);
  //   }
  // }
  return (
    <LayoutComp>
      <Form
        name="basic"
        labelCol={{ span: 8 }}
        wrapperCol={{ span: 16 }}
        style={{ maxWidth: 600 }}
        initialValues={{ remember: true }}
        onFinish={onFinish}
        onFinishFailed={onFinishFailed}
        autoComplete="off"
      >
        <Form.Item name="type" label="影院类型" rules={[{ required: true }]}>
          <Select
            placeholder="选择影院类型"
            allowClear
          >
            <Option value="1">影城</Option>
            <Option value="2">影投</Option>
          </Select>
        </Form.Item>
        <Form.Item<FieldType>
          label="密码"
          name="password"
          rules={[{ required: true, message: '请输入密码!' }]}
        >
          <Input.Password />
        </Form.Item>
        <Form.Item wrapperCol={{ offset: 8, span: 16 }}>
          <Button type="primary" htmlType="submit">
            提交
          </Button>
        </Form.Item>
      </Form>
      <div>
        <Table columns={columns} dataSource={data} />
      </div>
    </LayoutComp>
  )
}

export default App;